/* eslint-disable no-debugger */
import { DictValueEnum } from "@/components/DictTag";
import { http } from "@/utils/http/axios";
import _ from "lodash";

type DictValues = { type: string; value: DictValueEnum };
// 字典缓存管理器类
class DictionaryCacheManager {
	private storageKey = import.meta.env.VITE_GLOB_DICT_KEY;
	constructor() {}

	async getDict(type: string, isDigital: boolean = false): Promise<DictValueEnum> {
		const cachedData = localStorage.getItem(this.storageKey) as string;
		if (cachedData) {
			try {
				const cacheDictObj = JSON.parse(cachedData);
				const hasType = _.has(cacheDictObj, type);
				if (hasType) {
					return Promise.resolve(cacheDictObj[type]);
				} else {
					const data = await this.fetchAndCacheDictionary(type, isDigital);
					return Promise.resolve(data);
				}
			} catch (error) {
				console.error("Error parsing cached dictionary data:", error);
				return Promise.reject();
			}
		} else {
			const data = await this.fetchAndCacheDictionary(type, isDigital);
			return Promise.resolve(data);
		}
	}
	private async fetchAndCacheDictionary(type: string, isDigital: boolean): Promise<DictValueEnum> {
		return http
			.request<API.Response.BasicResponse>(
				{
					url: `/system/dict/data/type/${type}`,
					method: "GET"
				},
				{
					isTransformResponse: true
				}
			)
			.then(async (data: any) => {
				const opts: DictValueEnum = {};
				data.forEach((item: any) => {
					opts[item.dictValue] = {
						text: item.dictLabel,
						label: item.dictLabel,
						value: isDigital ? Number(item.dictValue) : item.dictValue,
						key: item.id,
						color: item.color
					};
				});
				return this.setStorage(type, opts).then(() => Promise.resolve(opts));
			})
			.catch(() => {
				return Promise.resolve({});
			});
	}
	private async setStorage(type: string, value: DictValueEnum) {
		const cachedData = localStorage.getItem(this.storageKey) as string;
		if (cachedData) {
			const cacheDictObj = JSON.parse(cachedData);
			cacheDictObj[type] = value;
			localStorage.setItem(this.storageKey, JSON.stringify(cacheDictObj));
			return Promise.resolve();
		} else {
			//保存
			const data = {
				[type]: value
			};
			localStorage.setItem(this.storageKey, JSON.stringify(data));
			return Promise.resolve();
		}
	}
}

export const dict = new DictionaryCacheManager();
